import java.util.Random;

public class Test03 {
    private static final int ARRAY_SIZE = 1000_0000;
    private static final int MAX_VALUE = 100;

    public static void main(String[] args) throws InterruptedException {
        //记录开始的时间
        long start = System.currentTimeMillis();
        //1.给定一个很长的数组（长度为1000w）,通过随机数的方式生成 1-100 之间的整数
        int[] array = new int[ARRAY_SIZE];
        //生成随机数，对数组进行填充
        Random random = new Random();
        for (int i = 0; i < ARRAY_SIZE; i++) {
            array[i] = random.nextInt(MAX_VALUE) + 1;
        }


        //2.创建两个线程 对数组内的元素进行求和
        //3.线程一计算偶数下标元素的和，线程二计算奇数下标元素的和

        //实例化操作类
        SumOperator operator = new SumOperator();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < ARRAY_SIZE; i += 2) {
                operator.addEvenSum(array[i]);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i < ARRAY_SIZE; i += 2) {
                operator.addOddSum(array[i]);
            }
        });

        //启动线程
        t1.start();
        t2.start();

        //等待线程结束
        t1.join();
        t2.join();

        //记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("计算结果为：" + operator.result());
        System.out.println("总耗时：" + (end - start) + "ms.");
    }
}

class SumOperator{
    long evenSum;//偶数和
    long oddSum;//奇数和

    public void addEvenSum(int num){
        evenSum += num;
    }
    public void addOddSum(int num){
        oddSum += num;
    }
    public long result() {
        System.out.println("偶数和：" + evenSum);
        System.out.println("奇数和：" + oddSum);
        return evenSum + oddSum;
    }
}

